package cn.iotab.iotkit.transport.api.common.id;

import cn.iotab.iotkit.transport.api.access.model.message.DeviceMessage;
import cn.iotab.iotkit.transport.api.access.model.message.DeviceMessageReply;
import lombok.Getter;

import java.util.Objects;

public class DeviceMessageKey {

    @Getter
    private final String productKey;
    @Getter
    private final String deviceId;
    @Getter
    private final String msgId;
    //缓存hashCode提高性能
    private final int hashCode;

    private DeviceMessageKey(String productKey, String deviceId, String msgId) {
        this.productKey = productKey;
        this.deviceId = deviceId;
        this.msgId = msgId;
        this.hashCode = Objects.hash(productKey, deviceId, msgId);
    }

    public static DeviceMessageKey of(String productKey, String deviceId, String msgId) {
        return new DeviceMessageKey(productKey, deviceId, msgId);
    }

    public static DeviceMessageKey of(DeviceMessage message) {
        String msgId = message.getMessageId();
        return DeviceMessageKey.of(message.getProductKey(), message.getDeviceId(), msgId);
    }

    public static DeviceMessageKey of(DeviceMessageReply message) {
        String msgId = message.getMessageId();
        return DeviceMessageKey.of(message.getProductKey(), message.getDeviceId(), msgId);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        DeviceMessageKey that = (DeviceMessageKey) o;
        return Objects.equals(productKey, that.productKey)
                && Objects.equals(deviceId, that.deviceId)
                && Objects.equals(msgId, that.msgId);
    }

    @Override
    public int hashCode() {
        return hashCode;
    }

    @Override
    public String toString() {
        return productKey + "_" + deviceId + "_" + msgId;
    }
}
